import React, { Component } from 'react';
import styled from 'styled-components/native';
import { Keyboard, AsyncStorage } from 'react-native';
import SVGImage from 'react-native-svg-uri';
import { graphql, compose } from 'react-apollo';
import { connect } from 'react-redux';

import { TOKEN } from '../types';
import { colors, logoURL } from '../utils/constants';
import { loginAndGoBack } from '../actions/user';
import Loading from '../components/Loading';
import LOGIN_MUTATION from '../graphql/mutations/login';

import { TextInputCom, RoundCornerButton, LinkText } from '../components/common';

const LOGO_SIZE = 72;
const LOGO_IMAGE_SIZE = 48;
const LOGO_RADIUS = LOGO_SIZE / 2;

const Root = styled.View`
  width: 100%;
  height: 100%;
  backgroundColor: ${ colors.WHITE };
  alignItems: center;
  justifyContent: flex-start;
`;

const LogoWrapper = styled.View`
  flexDirection: row;
  justifyContent: center;
`;

const LogoIcon = styled.View`
  width: ${ LOGO_SIZE };
  height: ${ LOGO_SIZE };
  borderRadius: ${ LOGO_RADIUS };
  borderWidth: 1;
  borderColor: ${ colors.DIVIDER };
  alignItems: center;
  justifyContent: center;
  marginBottom: 45;
`;

const Form = styled.View`
  width: 90%;
  marginTop: 35;
`;

const LoginButton = styled(RoundCornerButton) `
  marginTop: 30;
`;

const ErrorText = styled.Text`
  color: ${ colors.ERROR_RED };
  fontSize: 14;
`;

const HelpText = styled.View`
  marginTop: 5;
`;

class LoginScreen extends Component {

  state = {
    username: '',
    password: '',
    errors: null,
    loading: false
  }

  _onChangeText = (type, value) => this.setState({ [type]: value });

  _isReadyToSubmit = () => {
    if (!this.state.loading && this.state.username && this.state.password) {
      return true;
    }
    return false;
  }

  _login = async () => {
    Keyboard.dismiss();
    this.setState({ loading: true });

    const { username, password } = this.state;
    try {
      const { data } = await this.props.mutate({
        variables: {
          account: username,
          password
        }
      });

      await AsyncStorage.setItem(TOKEN, data.login.token);
      this.setState({ loading: false });
      this.props.loginAndGoBack();
    } catch (error) {
      this.setState({
        loading: false,
        errors: { message: error.graphQLErrors[0].message }
      });
    }
  }

  render() {
    return (
      <Root>
        <Form>
          <LogoWrapper>
            <LogoIcon>
              <SVGImage
                width={LOGO_IMAGE_SIZE} height={LOGO_IMAGE_SIZE}
                source={{ uri: logoURL }} />
            </LogoIcon>
          </LogoWrapper>
          <TextInputCom
            placeholder="手机号或邮箱"
            autoCapitalize="none"
            keyboardType="email-address"
            onChangeText={text => this._onChangeText("username", text)}
            blurOnSubmit={false}
            onSubmitEditing={() => this.password.focus()}
            returnKeyType="next"
            value={this.state.username || ''}
          />
          <TextInputCom
            innerRef={r => { this.password = r }}
            placeholder="密码"
            secureTextEntry
            onChangeText={text => this._onChangeText("password", text)}
            onSubmitEditing={() => {
              if (this._isReadyToSubmit()) {
                this._login();
              }
            }}
            returnKeyType="go"
            value={this.state.password || ''}
          />
          {
            this.state.errors && <ErrorText>{this.state.errors.message}</ErrorText>
          }
          <LoginButton disabled={!this._isReadyToSubmit()} onPress={this._login} text="登录">
            {
              this.state.loading && <Loading size="small" color={colors.WHITE} />
            }
          </LoginButton>
          <HelpText>
            <LinkText url="https://www.baidu.com">登录遇到问题？</LinkText>
          </HelpText>
        </Form>
      </Root>
    );
  }
}

export default compose(
  graphql(LOGIN_MUTATION),
  connect(null, { loginAndGoBack })
)(LoginScreen);
